//
//  DYJiudianHeadView.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/11.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import SDCycleScrollView
import SwiftWeb

class DYJiudianHeadView: SYBaseView  , UITableViewDelegate, UITableViewDataSource {
    
    var videoIndex: Int = 1000
    var videoUrl: String = ""
    let fullScreenVC = SYFullScreenViewController()
    var player: SYPlayer!
    var pics: [String] = []
    
    var model: DYZSDetailModel!
    var location = LocationManager()
    let delegate  = DYLocationDelegate()
    var body: [String: Any] = [:]
    var tableView: UITableView!
    
    let middleBg: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        v.layer.cornerRadius = 5
        v.layer.shadowColor = UIColor(hex: 0xB3B3B3).cgColor
        v.layer.shadowOpacity = 0.5//阴影透明度
        v.layer.shadowOffset = CGSize.zero///阴影偏移量,四周
        v.layer.shadowRadius = 5//阴影半径  shadowPathWidth：阴影宽度
        return v
    }()
    
    let name: UILabel = {
        let v = UILabel()
        v.textColor = UIColor(hex: 0x1E1E1E)
        v.font = 18.autoBoldFontSize()
        return v
    }()
    
    let tagLb: UILabel = {
        let v = UILabel()
        v.textColor = UIColor(hex: 0xFDA62B)
        v.font = 11.autoFontSize()
        v.backgroundColor = UIColor(hex: 0xFFF1D2)
        return v
    }()
    
    let shoucang: UIButton = {
        let v: UIButton  = UIButton()
        v.setImage(UIImage(named: "wujiaoxing"), for: .normal)
        v.setImage(UIImage(named: "wujiaoxing_select"), for: .selected)
        return v
    }()
    
    let back: UIButton = {
        let v: UIButton  = UIButton()
        v.setImage(UIImage(named: "nav_back"), for: .normal)
        return v
    }()
    
    var pageView: UILabel = {
        let v = UILabel()
        v.textColor = .white
        v.font = 12.autoFontSize()
        v.textAlignment = .center
        v.backgroundColor = UIColor(white: 0, alpha: 0.5)
        v.layer.cornerRadius = 9.autoWidth()
        v.layer.masksToBounds = true
        return v
    }()
    
    let cycleScrollView: SDCycleScrollView = SDCycleScrollView(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 243.5.autoWidth() + STATUSBAR_HEIGHT))
    
    override func initViews() {
        self.backgroundColor = Constant.bgViewColor
        gpsService()
        
        
        back.addAction {
            self.currentVC.navigationController?.popViewController(animated: true)
        }
        shoucang.addTarget(self, action: #selector(shoucangAction), for: .touchUpInside)
        //        cycleScrollView.placeholderImage = UIImage(named: "banner")
        // 添加到view
        cycleScrollView.delegate = self
        setTableView()
        self.addSubview(cycleScrollView)
        self.addSubview(shoucang)
        self.addSubview(back)
        cycleScrollView.addSubview(pageView)
        
        self.addSubview(middleBg)
        middleBg.addSubview(name)
        middleBg.addSubview(tagLb)
        middleBg.addSubview(self.tableView!)
        
        back.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(STATUSBAR_HEIGHT)
            make.height.equalTo(48.autoWidth())
            make.width.equalTo(30.autoWidth())
        }
        shoucang.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.top.equalToSuperview().offset(13.autoWidth() + STATUSBAR_HEIGHT)
            make.height.equalTo(19.autoWidth())
            make.width.equalTo(18.autoWidth())
        }
        
        middleBg.snp.makeConstraints { (make) in
            make.top.equalTo(cycleScrollView.snp.bottom).offset(-31.autoWidth())
            make.left.equalToSuperview().offset(15.0.autoWidth())
            make.right.equalToSuperview().offset(-15.0.autoWidth())
            make.height.equalTo(75.0.autoWidth())
        }
        
        name.snp.makeConstraints { (make) in
            make.top.equalTo(middleBg).offset(14.5.autoWidth())
            make.left.equalToSuperview().offset(15.0.autoWidth())
            make.height.equalTo(17.0.autoWidth())
        }
        
        tagLb.snp.makeConstraints { (make) in
            make.centerY.equalTo(name)
            make.left.equalTo(name.snp.right).offset(5.0.autoWidth())
            make.height.equalTo(15.0.autoWidth())
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(name.snp.bottom).offset(7.0.autoWidth())
            make.left.right.equalToSuperview()
            make.height.equalTo(34.0.autoWidth())
        }
        
    }
    
    func configure(_ model: DYZSDetailModel) {
        self.model = model
        pics = []
        if let l = model.imgUrl {
            let urls = l.components(separatedBy: ",")
            for (_, value) in urls.enumerated() {
                pics.append(IMGIP + (value))
            }
        }
        self.cycleScrollView.imageURLStringsGroup = pics
        
        name.text = model.name
        tagLb.text = "  \(model.label ?? "")  "
        pageView.text = "\(1) / \(pics.count)"
        
        self.location.startLocation()
        self.tableView.reloadData()
    }
    
    // 定位
    fileprivate func gpsService() {
        
        delegate.location = location
        delegate.currentVC = self.currentVC
        delegate.gpsClosure = {[weak self] (lon,lat) in
            if let `self` = self {
                
                if let m = self.model {
                    self.body = ["startLat": "\(lat)", "startLon": "\(lon)", "endLat": "\(m.latitude ?? "")", "endLon": "\(m.longitude ?? "")", "startAddress": "", "endAddress": ""]
                }
            }
        }
        location.locationProtocol = delegate
        //只获取一次
//        isOnece = true
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect.zero, style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView!.register(DYDaolanDetailHeadCell.self, forCellReuseIdentifier: "Cell")
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: DYDaolanDetailHeadCell? = tableView.dequeueReusableCell(withIdentifier: "Cell") as? DYDaolanDetailHeadCell
        cell?.selectionStyle = .none
        cell?.pic.image = UIImage(named: "location_daolan")
        if nil != self.model {
            cell?.nameLb.text = self.model.address
        }
        cell?.locationLb.text = "地图导航 >"
        cell?.locationLb.textColor = Constant.blueColor
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            if body.isEmpty {
                return
            }
            GaodeManager.routePlanning(body)
        }
    }
    
    @objc func shoucangAction() {
        
    }
}


extension DYJiudianHeadView:SDCycleScrollViewDelegate {
    
    func customCollectionViewCellClass(for view: SDCycleScrollView!) -> AnyClass! {
        return DYDaolanDetailLunboCell.self
    }
    
    func setupCustomCell(_ cell: UICollectionViewCell!, for index: Int, cycleScrollView view: SDCycleScrollView!) {
        let cell: DYDaolanDetailLunboCell = (cell as! DYDaolanDetailLunboCell);
        cell.pic.kf.setImage(with: URL(string: pics[index]))
        cell.videoPic.addAction {[weak self] in
            if let `self` = self {
                self.playVideo()
                self.cycleScrollView.autoScroll = false
            }
        }
        if index == videoIndex {
            cell.videoPic.isHidden = false
        } else {
            cell.videoPic.isHidden = true
        }
        
    }
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didScrollTo index: Int) {
        pageView.text = "\(index+1) / \(pics.count)"
    }
}

extension DYJiudianHeadView:SYPlayerDelegate {
    //
    //    func playVideo() {
    //
    //        let model = WMPlayerModel()
    //        model.title = ""
    //        model.videoURL = URL(string: testMP4)
    //        player = SYPlayer(model: model)
    //        self.cycleScrollView.addSubview(player)
    //        // 不能用约束，后面改变frame有问题
    //        let originalFrame = cycleScrollView.frame
    //        player.frame = originalFrame
    //        player.play()
    //        player.delegate = self
    //
    //        fullScreenVC.syPlayer = player
    //        fullScreenVC.originalFrame = originalFrame
    //        fullScreenVC.superView = self.cycleScrollView
    //    }
    //
    //
    //    func wmplayer(_ wmplayer: SYPlayer!, clickedFullScreenButton fullScreenBtn: UIButton!) {
    //
    //        if fullScreenBtn.isSelected == true {
    //            fullScreenVC.fullScreenAction()
    //            self.currentVC.sy_push(fullScreenVC, false)
    //        } else {
    //            fullScreenVC.backAction()
    //        }
    //    }
    //
    //    func wmplayer(_ wmplayer: SYPlayer!, clickedClose backBtn: UIButton!) {
    //        fullScreenVC.backAction()
    //    }
    
    // 播放视频
    func playVideo() {
        
        let model = WMPlayerModel()
        model.videoURL = URL(string: videoUrl)
        player = SYPlayer(model: model)
        self.addSubview(player!)// 播放音频需要addsubview，不用设置frame
        
        player!.play()
        player!.delegate = self
        
        /*
         NSURL *URL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"4k" ofType:@"mp4"]];
         playerModel.videoURL = [NSURL URLWithString:[URL absoluteString]];
         */
        
        fullScreenVC.syPlayer = player!
        //        fullScreenVC.originalFrame = originalFrame
        //        fullScreenVC.superView = self.videoContent
        
        fullScreenVC.shupingAction()
        self.currentVC.vg_present(fullScreenVC, animated: false)
        
    }
    
    func wmplayer(_ wmplayer: SYPlayer!, clickedFullScreenButton fullScreenBtn: UIButton!) {
        
        if fullScreenBtn.isSelected == true {
            fullScreenVC.fullScreenAction()
        } else {
            fullScreenVC.shupingAction()
        }
    }
    
    func wmplayer(_ wmplayer: SYPlayer!, clickedClose backBtn: UIButton!) {
        fullScreenVC.backAction()
        player!.pause()
        player = nil
        self.cycleScrollView.autoScroll = true
    }
}
